// 连接测试工具
import axios from 'axios'

export const connectionTest = {
  // 测试后端连接
  async testBackendConnection() {
    console.log('=== 后端连接测试 ===')
    
    try {
      // 直接测试后端地址
      const directResponse = await axios.get('http://localhost:8891/api/devices', {
        timeout: 5000,
        params: { pageNum: 1, pageSize: 1 }
      })
      console.log('直接连接后端成功:', directResponse.data)
      return { success: true, method: 'direct', data: directResponse.data }
    } catch (error) {
      console.error('直接连接后端失败:', error.message)
    }
    
    try {
      // 通过代理测试
      const proxyResponse = await axios.get('/api/devices', {
        timeout: 5000,
        params: { pageNum: 1, pageSize: 1 }
      })
      console.log('通过代理连接成功:', proxyResponse.data)
      return { success: true, method: 'proxy', data: proxyResponse.data }
    } catch (error) {
      console.error('通过代理连接失败:', error.message)
    }
    
    return { success: false, error: '所有连接方式都失败' }
  },

  // 测试网络连通性
  async testNetworkConnectivity() {
    console.log('=== 网络连通性测试 ===')
    
    const tests = [
      { name: '本地回环', url: 'http://127.0.0.1:8891/api/devices' },
      { name: 'localhost', url: 'http://localhost:8891/api/devices' },
      { name: '代理路径', url: '/api/devices' }
    ]
    
    for (const test of tests) {
      try {
        console.log(`测试 ${test.name}: ${test.url}`)
        const response = await axios.get(test.url, { timeout: 3000 })
        console.log(`✅ ${test.name} 连接成功:`, response.status)
      } catch (error) {
        console.log(`❌ ${test.name} 连接失败:`, error.message)
      }
    }
  },

  // 检查后端服务状态
  async checkBackendStatus() {
    console.log('=== 后端服务状态检查 ===')
    
    try {
      // 尝试访问根路径
      const response = await axios.get('http://localhost:8891/', { timeout: 3000 })
      console.log('后端服务根路径响应:', response.status)
    } catch (error) {
      console.log('后端服务根路径访问失败:', error.message)
    }
    
    try {
      // 尝试访问健康检查端点（如果存在）
      const response = await axios.get('http://localhost:8891/health', { timeout: 3000 })
      console.log('健康检查响应:', response.data)
    } catch (error) {
      console.log('健康检查失败:', error.message)
    }
  },

  // 运行完整诊断
  async runFullDiagnosis() {
    console.log('🔍 开始完整连接诊断...')
    
    await this.testNetworkConnectivity()
    await this.checkBackendStatus()
    const result = await this.testBackendConnection()
    
    console.log('📊 诊断结果:', result)
    
    if (result.success) {
      console.log('✅ 连接测试成功！')
      return { success: true, message: '后端连接正常' }
    } else {
      console.log('❌ 连接测试失败！')
      return { 
        success: false, 
        message: '无法连接到后端服务，请检查：\n1. 后端服务是否在8891端口启动\n2. 后端服务是否正常运行\n3. 防火墙设置\n4. 网络连接' 
      }
    }
  }
}

// 在浏览器控制台中可用的全局函数
if (typeof window !== 'undefined') {
  window.connectionTest = connectionTest
}
